package com.jinlongchen.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jinlongchen.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*
1、判断用户是否登录
2、根据API结果格式规定，构造相应的对象
3、把对象序列化成JSON字符串
4、将结果写入resp对象中
* */
@WebServlet("/api/current-user.json")
public class CurrentUserApi extends HttpServlet{
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        //这里的代码用于临时测试，一会就删掉了
//        {
//            User user = new User();
//            user.uid = 998;
//            user.nickname = "告诉啊";
//            user.username = "whatfuck";
//            HttpSession session = req.getSession();
//            session.setAttribute("currentUser",user);
//        }

        //判定目前是否有用户处于登录状态
        HttpSession session = req.getSession();
        User currentUser =(User)session.getAttribute("currentUser");
        Object reslut;
        if (currentUser == null){
            //用户未登录

            //使用匿名类，可以不用专门去定义一个结果对象
            reslut = new Object(){
                public boolean logged = false;
            };
        }else {
            //用户已登陆
            reslut = new Object(){
                public boolean logged = true;
                public User user = currentUser;
            };
        }

        //将对象序列化成JSON字符串
        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(reslut);

        //将JSON字符串放入resp对象中
        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().println(json);
    }
}
